<template>
  <div>
    <el-card class="card" style="max-width: 1200px">
      <div>
        <div class="head">
          <div class="userInfo">
            <div class="text">学生信息表</div>
          </div>
          <div class="btn-area">
            <el-button type="primary" style="margin-right: 5px" @click="addStuInfo">新增</el-button>
            <el-upload
              class="handle"
              action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :limit="1"
              :on-exceed="handleExceed"
            >
              <el-button type="primary">上传</el-button>
            </el-upload>
          </div>
        </div>
        <el-table :data="filteredTableData" border style="width: 100%">
          <el-table-column prop="name" label="姓名" />
          <el-table-column prop="stuNum" label="学号" />
          <el-table-column prop="className" label="班级">
            <template #header>
              <span>班级</span>
              <el-dropdown trigger="click" @command="filterStudents">
                <el-icon class="select"><ArrowDown /></el-icon>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-for="clazz in classes"
                      :key="clazz"
                      :command="clazz"
                      @click="selectStudentByClazzClick(clazz)"
                    >
                      {{ clazz }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
            <template #default="scope">
              {{ scope.row.className }}
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="电话" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                class="handle"
                size="small"
                type="primary"
                @click="updateStuInfo(scope.row)"
              >
                修改
              </el-button>
              <el-button
                class="handle"
                size="small"
                type="primary"
                @click="studyRecordDialogRef?.open(scope.row.id)"
              >
                进度
              </el-button>
              <el-button
                class="handle"
                size="small"
                type="danger"
                @click="deleteStuInfo(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <el-dialog
      v-model="dialogVisible1"
      :title="studentInfo + '学生信息'"
      width="500"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="ruleForm.name" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="学号" prop="stuNum">
          <el-input v-model="ruleForm.id" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="班级" prop="className">
          <el-input v-model="ruleForm.class" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="ruleForm.tel" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetForm">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <study-record-dialog ref="studyRecordDialogRef" />
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessageBox, ElMessage, UploadProps } from "element-plus";
import StudyRecordDialog from "@/views/student/components/studyRecordDialog.vue";
import { getStudentInfo } from "@/api/student";
//import { getAccessToken } from "@/utils/auth";

//const uploadUrl = import.meta.env.VITE_APP_BASE_API + "/teacher/importStudentInfo";
// const headers = ref({
//   token: getAccessToken(),
// });
const dialogVisible1 = ref(false);
const studentInfo = ref("新增");

const handleClose = async (done: () => void) => {
  await ElMessageBox.confirm("是否要关闭?");
  done();
};
//const uploadRef = ref<UploadInstance>();
// const handleUploadSuccess = (response: any, file: any, fileList: any) => {
//   console.log(response, file, fileList);
//   if (response.code === 0) {
//     ElMessage.success("上传成功");
//   } else {
//     ElMessage.error(response.msg);
//   }
// };
const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log(uploadFile);
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 1, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  );
};

const beforeRemove: UploadProps["beforeRemove"] = (uploadFile) => {
  return ElMessageBox.confirm(`Cancel the transfer of ${uploadFile.name} ?`).then(
    () => true,
    () => false
  );
};

// const handleUpload = async (data: any) => {
//   const fromData = new FormData();
//   fromData.set("file", data.file);
//   console.log(data, "学生信息");
//   await uploadPoint(fromData);
//   uploadRef.value?.clearFiles();
//   ElMessage.success("上传成功");
// };
interface StuInfo {
  stuNum: string;
  name: string;
  className: string;
  phone: string;
  email: string;
}
const tableData = reactive<StuInfo[]>([]);
// 班级列表
const classes = ref(["软件1班", "软件2班"]);
const selectedClass = ref("");
const selectStudentByClazz = async () => {
  const res = await getStudentInfo({ className: "" });
  console.log(res, "学生数组");
  selectedStudentByClass.value = res;
  tableData.push(...selectedStudentByClass.value);
};
const selectStudentByClazzClick = async (item: any) => {
  console.log(item, "item");
};
const selectedStudentByClass = ref();
// 筛选后的学生表
const filteredTableData = computed(() => {
  if (!selectedClass.value) {
    return tableData;
  } else {
    return tableData.filter((item) => item.className === selectedClass.value);
  }
});
//筛选学生
const filterStudents = (clazz: string) => {
  selectedClass.value = clazz;
};
const ruleForm = reactive({
  name: "",
  id: "",
  class: "",
  tel: "",
  email: "",
});
const rules = reactive({
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 10, message: "长度应为2-10" },
  ],
  id: [{ required: true, message: "请输入学号", trigger: "blur" }],
  class: [{ required: true, message: "请输入班级", trigger: "blur" }],
  tel: [
    { required: true, message: "请输入电话", trigger: "blur" },
    { pattern: /^(\d{11})$/, message: "电话号码必须是11位的数字" },
  ],
  email: [{ required: true, message: "请输入邮箱" }],
});
const studyRecordDialogRef = ref();

let currentRow = {
  name: "",
  class: "",
  id: "",
  tel: "",
  email: "",
};
const ruleFormRef = ref();

const submitForm = () => {
  //合法性判断
  ruleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      if (studentInfo.value === "新增") {
        tableData.push({
          name: ruleForm.name,
          stuNum: ruleForm.id,
          className: ruleForm.class,
          phone: ruleForm.tel,
          email: ruleForm.email,
        });
        dialogVisible1.value = false;
        ElMessage.success("新增成功");
      } else {
        // 使用 currentRow.id 来查找索引
        const index = tableData.findIndex((item) => item.stuNum === currentRow.id);
        if (index !== -1) {
          tableData[index].name = ruleForm.name;
          tableData[index].className = ruleForm.class;
          tableData[index].phone = ruleForm.tel;
          // 如果 id 被修改，更新 id
          tableData[index].stuNum = ruleForm.id;
          tableData[index].email = ruleForm.email;
          currentRow.id = ruleForm.id; // 更新 currentRow 的 id
        }
        dialogVisible1.value = false;
        ElMessage.success("修改成功");
      }
    } else {
      ElMessage.error("填写内容不合法");
    }
  });
};

const resetForm = () => {
  dialogVisible1.value = false;
};
const openDialog = (isAdd: boolean) => {
  if (isAdd) {
    studentInfo.value = "新增";
  } else {
    studentInfo.value = "修改";
  }
  dialogVisible1.value = true;
};
const addStuInfo = () => {
  openDialog(true);
  ruleForm.id = "";
  ruleForm.class = "";
  ruleForm.tel = "";
  ruleForm.name = "";
};
const updateStuInfo = (row: StuInfo) => {
  Object.assign(currentRow, row);
  ruleForm.id = row.stuNum;
  ruleForm.class = row.className;
  ruleForm.tel = row.phone;
  ruleForm.name = row.name;
  ruleForm.email = row.email;
  openDialog(false);
};
const deleteStuInfo = (id: string) => {
  ElMessageBox.confirm("确定删除?")
    .then(() => {
      const index = tableData.findIndex((item) => item.stuNum === id);
      tableData.splice(index, 1);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

onMounted(async () => {
  await selectStudentByClazz();
});
</script>
<style scoped lang="scss">
.card {
  margin: 20px;
}
.userInfo {
  width: 100px;
  margin: 10px 20px;
  font-weight: bold;
}
.head {
  position: relative;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  width: 100%;
  height: 50px;
  background-color: #ffffff;
  border: 1px solid #ebeef5;
  border-bottom: 0;
}
#main {
  float: left;
}
.bar {
  display: flex;
  float: left;
  width: 50%;
}
.handle {
  width: 28%;
}
.el-button {
  margin-right: 10px;
  margin-left: 0;
}

.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}
.btn-area {
  display: flex;
  flex-direction: row;
  position: absolute;
  right: 10px;
  margin-top: 10px;
}
.text {
  display: flex;
  position: absolute;
  left: 10px;
  margin: 10px;
}
.knowledge {
  width: 400px;
  margin: 0 10px 10px 30px;
}
.select {
  margin-left: 120px;
  margin-top: 5px;
}
</style>
